package com.bulk.threadLocal;

import java.util.HashMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 演示内存泄露
 *
 * @author 散装java
 * @since 2022/6/5
 */
public class ThreadLocalOut {
    static ThreadLocal<BizData> LOCAL = new ThreadLocal<>();

    // 创建一个线程池
    static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5,
            5,
            1,
            TimeUnit.MINUTES,
            new LinkedBlockingDeque<>());





    // 创建一个静态内部类，用来作为数据
    static class BizData {
        // 10M
        private byte[] data = new byte[1024 * 1024 * 10];
    }

    // -Xms125 -Xmx125
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 1000; i++) {
            executor.execute(() -> {
                BizData bizData = new BizData();
//                HashMap<Thread, BizData> map = new HashMap<>();
//                map.put(Thread.currentThread(),bizData);
//                // 做一些业务操作。
//                map.get(Thread.currentThread());

                ThreadLocal<Object> local = new ThreadLocal<>();
                local.set(bizData);
                // 做一些业务操作
                local.get();
                local.remove();
                System.out.println(Thread.currentThread().getName() + " 执行完成 ");
            });
        }
    }






    /**
     * 模拟业务数据处理方法
     */
    public static void Biz() {
        try {
            // 获取数据
            BizData bizData = LOCAL.get();
            // 模拟业务执行
            System.out.println(Thread.currentThread().getName() + " 业务执行 bizData = " + bizData);
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
